package webapp.backOffice.servlet;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import modele.utilisateur.Admin;
import webapp.tools.Auth;
import dao.utilisateur.AdminDAO;

/**
 *
 * @author Hitscream
 */
@WebServlet(name = "LoginAdmin", urlPatterns = {"/admin","/admin/"})
public class LoginAdmin extends HttpServlet {


    /**
     * Affiche la page de connexion.<br/>
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException 
    {
        if(Auth.isAdmin(request.getSession()))
        {
            response.sendRedirect(request.getContextPath() + "admin/index");
        }
        else
        {
            RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/WEB-INF/viewBackoffice/login.jsp");
            dispatcher.forward(request, response);
        }
    }

    /**
     * Traite la tentative de connexion.
     * 
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        //Parametres POST
        String login = request.getParameter("login");
        String pass = request.getParameter("pass");
        
        
        //Recherche de l'utilisateur
        Admin myUser = new AdminDAO().retrieveByLoginPass(login, pass);
        if(myUser == null)  //Teste l'existence du code client
        {
            request.setAttribute("error", "Les identifiants saisis sont erronés.");
        }
        
        
        //Reponse de la requete POST
        if(myUser != null)
        {
            //Connexion & creation de la session
            HttpSession session = request.getSession();
            session.setAttribute("admin", myUser);
            response.sendRedirect(request.getContextPath() +"/admin/index");
        }
        else
        {
            //Redirection vers la page de login
            doGet(request, response);
        }
    }
}
